package com.blog4j.server.modules.sms.utils;

import com.blog4j.common.enums.ErrorEnum;
import com.blog4j.common.exception.Blog4jException;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author 98k灬
 * @version v1.0.0
 * @Description : 功能描述
 * @Create on : 2024/7/27 18:12
 **/
@Slf4j
public class SmsUtil {
    public static void sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            log.info("短信发送结果: [{}]", result);
        } catch (IOException exception) {
            throw new Blog4jException(ErrorEnum.IO_ERROR);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException exception) {
                throw new Blog4jException(ErrorEnum.SEND_PHONE_CODE_ERROR);
            }
        }
    }

    public static String createMsmCode() {
        long newCode = 0;
        for (int j = 0; j < 100; j++) {
            newCode = (int) ((Math.random() * 9 + 1) * 100000);
        }
        return String.valueOf(newCode);
    }

    public static String getMD5String(String rawString) throws NoSuchAlgorithmException {
        String[] hexArray = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(rawString.getBytes());
        byte[] rawBit = md.digest();
        String outputMD5 = " ";
        for (int i = 0; i < 16; i++) {
            outputMD5 = outputMD5 + hexArray[rawBit[i]>>>4 & 0x0f];
            outputMD5 = outputMD5 + hexArray[rawBit[i] & 0x0f];
        }
        return outputMD5.trim();
    }
}
